//
//  MCNetworkMonitoring.m
//  iMooc
//
//  Created by CoderXSLee on 13/5/7.
//  Copyright © 2013年 李雪松. All rights reserved.
//

#import "MCTip.h"
#import "MCNetworkMonitoring.h"


#if __has_include(<AFNetworking/AFNetworking.h>)
#import <AFNetworking/AFNetworking.h>
#elif __has_include("AFNetworking.h")
#import "AFNetworking.h"
#endif

#include<netdb.h>
#include<unistd.h>

#define manager [AFNetworkReachabilityManager sharedManager]

NSString * const _kMCNetworkStringWWAN          = @"手机网络";
NSString * const _kMCNetworkStringWiFi          = @"WiFi网络";
NSString * const _kMCNetworkStringNone          = @"无网络连接";
NSString * const _kMCNetworkStringUnknown       = @"未知的网络连接";

NSString * const MCNetworkingStatusChangedNotification = @"MCNetworkingStatusChangedNotification";

@interface MCNetworkMonitoring ()

@end

@implementation MCNetworkMonitoring


- (void)stopMonitoring {
    [manager stopMonitoring];
}

// 开始监听网络状态
- (void)startMonitoring {
    [manager startMonitoring];
    _networkStatus = MC_NETWORK_STATUS_WWAN;
    [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        switch (status) {
            case AFNetworkReachabilityStatusUnknown:
                [self reachabilityStatusChanged:MC_NETWORK_STATUS_Unknown];
                break;
            case AFNetworkReachabilityStatusNotReachable:
                [self reachabilityStatusChanged:MC_NETWORK_STATUS_None];
                break;
            case AFNetworkReachabilityStatusReachableViaWWAN:
                [self reachabilityStatusChanged:MC_NETWORK_STATUS_WWAN];
                break;
            case AFNetworkReachabilityStatusReachableViaWiFi:
                [self reachabilityStatusChanged:MC_NETWORK_STATUS_WiFi];
                break;
        }
    }];
}

/// 网络状态改变的回调
- (void)reachabilityStatusChanged:(MCNetworkStatus)status {
    // 判断 WiFi 是否连接互联网，未接入互联网或网络状态很差时，将会阻塞线程。
    // _networkStatus = [self isConnectInternet]?status:MC_NETWORK_STATUS_None;
    _networkStatus = status;
    [MCTip showHint:self.changeTip?[self statusString]:@""];
    [[NSNotificationCenter defaultCenter] postNotificationName:MCNetworkingStatusChangedNotification object:nil];
}

/// 网络状态描述
- (NSString *)statusString {
    if (self.networkStatus == MC_NETWORK_STATUS_Unknown) {
        return _kMCNetworkStringUnknown;
    }else if (self.networkStatus == MC_NETWORK_STATUS_None) {
        return _kMCNetworkStringNone;
    }else if (self.networkStatus == MC_NETWORK_STATUS_WiFi){
        return _kMCNetworkStringWiFi;
    }else if (self.networkStatus == MC_NETWORK_STATUS_WWAN){
        return _kMCNetworkStringWWAN;
    }else {
        return @"";
    }
}

- (BOOL)isConnectInternet {
    // #include<unistd.h> #include<netdb.h>
    char *hostname;
    struct hostent *hostinfo;
    hostname = "baidu.com";
    hostinfo = gethostbyname(hostname);
    bool isConnect = (hostinfo == NULL)?NO:YES;
    NSLog(isConnect?@"当前网络已连接互联网":@"当前网络未连接互联网");
    return isConnect;
}

- (BOOL)isConnectInternet_1 {
    __block BOOL isConnect = NO;
    NSString *urlString = @"http://captive.apple.com/";
    // 使用信号量实现NSURLSession同步请求
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    [[[NSURLSession sharedSession] dataTaskWithURL:[NSURL URLWithString:urlString] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        NSScanner *theScanner;
        NSString *text = nil;
        theScanner = [NSScanner scannerWithString:result];
        while ([theScanner isAtEnd] == NO) {
            [theScanner scanUpToString:@"<" intoString:NULL] ;
            [theScanner scanUpToString:@">" intoString:&text] ;
            result = [result stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%@>", text] withString:@""];
        }
        NSString *resultString = [result stringByReplacingOccurrencesOfString:@"\n" withString:@""];
        isConnect = [resultString isEqualToString:@"SuccessSuccess"] ? YES : NO;
        NSLog(isConnect?@"当前网络已连接互联网":@"当前网络未连接互联网");
        dispatch_semaphore_signal(semaphore);
    }] resume];
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
    return isConnect;
}

@end


/// 单例的实现
@implementation MCNetworkMonitoring (Singleton)
static id _instace;
+ (instancetype)sharedInstance {
    static dispatch_once_t onceToken;
    static MCNetworkMonitoring *instance = nil;
    dispatch_once(&onceToken, ^{
        instance = [[super allocWithZone:NULL] init];
    });
    return instance;
}
- (id)copyWithZone:(NSZone *)zone { return _instace; }
+ (id)allocWithZone:(struct _NSZone *)zone { return [self sharedInstance]; }
@end
